package com.uchengwang.ui.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.bean.MoreBean;
import com.uchengwang.ui.cm_ui.login.bean.WXTokenBean;
import com.uchengwang.ui.cm_ui.login.bean.WXUserInfoBean;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by U城网 on 2017/8/20.
 */

public class ShareToWxUtils {
    private static IWXAPI api;
    private static ShareToWxUtils utils;

    private String WX_APP_SECRET = "0586d289c62378c3ee1591a024642e95";//微信密钥
    private String WX_APP_ID = "wxa155371e919eb6c5";//微信APPID

    public static ShareToWxUtils getUtils(Context context) {
        if (utils == null || api == null){
            utils = new ShareToWxUtils(context);
        }
        return utils;
    }

    private ShareToWxUtils(Context context){
        // 微信注册初始化
        api = WXAPIFactory.createWXAPI(context.getApplicationContext(), WX_APP_ID, true);
        api.registerApp(WX_APP_ID);
    }

    /**
     * 获取微信的初始化对象
     * */
    public IWXAPI getWXAPI(Context context){
        if (api == null){
            utils = new ShareToWxUtils(context);
        }
        return api;
    }


    /**
     * 分享到微信 朋友圈
     * */
    public void share(final Context context, View view, final String url, final String title, final String desc){
        final List<MoreBean> beanList = new ArrayList<MoreBean>();

        beanList.add(new MoreBean(R.drawable.selector_share_wx, "微信朋友"));
        beanList.add(new MoreBean(R.drawable.selector_share_friend, "微信朋友圈"));

        PopupUtils.getUtils().bottomMore(context, view, beanList, new PopupUtils.OnItemPopupClickListener() {
            @Override
            public void onItemClick(int index, String t) {
                PopupUtils.getUtils().dismiss();

                Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.weixin_share);

                switch (index){
                    case 0://发送给朋友
                        ShareToWxUtils.getUtils(context).shareUrl(url, title, desc, bitmap, SendMessageToWX.Req.WXSceneSession);
                        break;
                    case 1://转发到朋友圈
                        ShareToWxUtils.getUtils(context).shareUrl(url, title, desc, bitmap, SendMessageToWX.Req.WXSceneTimeline);
                        break;
                }

            }
        });
    }



    /**
     * 分享网页到朋友圈或者好友，视频和音乐的分享和网页大同小异，只是创建的对象不同。
     * 详情参考官方文档：*
     * @param url         网页的url
     * @param title       显示分享网页的标题
     * @param description 对网页的描述
     * @param scene       分享方式：好友还是朋友圈
     */
    public boolean shareUrl(String url, String title, String description, Bitmap thumb,  int scene) {
        //初试话一个WXWebpageObject对象，填写url
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = url;
        return share(webPage, title, description, thumb, scene);
    }

    /**
     * WXSceneSession转发到微信会话框  WXSceneTimeline转发到微信朋友圈
     * @param thumb 分享到微信的图片  大小不能超过32k
     * */
    private boolean share(WXMediaMessage.IMediaObject mediaObject, String title, String description, Bitmap thumb, int scene) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(UChengApplication.getContext(), "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
            return false;
        }

        //初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(mediaObject);
        if (!TextUtils.isEmpty(title)) {
            msg.title = title;
        }
        if (!TextUtils.isEmpty(description)) {
            msg.description = description;
        }
        if (thumb != null) {
            msg.setThumbImage(thumb);
//            thumb.recycle();
        }
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = scene;
        return api.sendReq(req);
    }

    private static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 微信三方登录
     * */
    public void wxLogin(){
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";//
//                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
        req.state = "ucity_wechat_login";
        api.sendReq(req);
    }

    /**
     * 微信根据code获取Access_token
     * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     请求方式:GET
     * */
    public void getWxTokenByCode(Activity activity, String code, final OnHttpResultSingleListener<WXTokenBean> listener){
        MapRequest map = new MapRequest();
        map.put("appid", WX_APP_ID);
        map.put("secret", WX_APP_SECRET);
        map.put("code", code);
        map.put("grant_type", "authorization_code");
        HttpManager.newInstance(activity).queryOther(IHttpManager.RequestMethod.GET, "https://api.weixin.qq.com/sns/oauth2/access_token", map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "微信回调信息="+msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "微信回调信息="+data);
                if (!TextUtils.isEmpty(data)){
                    WXTokenBean bean = JsonUtils.getManager().stringToBean(data, WXTokenBean.class);
                    listener.onResult(status, "", bean);
                }else {
                    listener.onResult(status, "", null);
                }
            }
        });
    }

    /**
     * 微信刷新或续期access_token使用
     * https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
     * */
    public void wxRefreshToken(Activity activity, String refreshToken, final OnHttpResultSingleListener<WXTokenBean> listener){
        MapRequest map = new MapRequest();
        map.put("appid", WX_APP_ID);
        map.put("grant_type", "refresh_token");
        map.put("refresh_token", refreshToken);
        HttpManager.newInstance(activity).queryOther(IHttpManager.RequestMethod.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token", map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "微信回调信息="+msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "微信回调信息="+data);
                if (!TextUtils.isEmpty(data)){
                    WXTokenBean bean = JsonUtils.getManager().stringToBean(data, WXTokenBean.class);
                    listener.onResult(status, "", bean);
                }else {
                    listener.onResult(status, "", null);
                }
            }
        });
    }

    /**
     * 获取微信用户的信息
     * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
     * */
    public void getWXUserInfo(final Activity activity, String accessToken, String openID, final OnHttpResultSingleListener<WXUserInfoBean> listener){
        MapRequest map = new MapRequest();
        map.put("access_token", accessToken);
        map.put("openid", openID);
        HttpManager.newInstance(activity).queryOther(IHttpManager.RequestMethod.GET, "https://api.weixin.qq.com/sns/userinfo", map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "微信回调信息="+msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "微信回调信息="+data);
                if (!TextUtils.isEmpty(data)){
                    WXUserInfoBean bean = JsonUtils.getManager().stringToBean(data, WXUserInfoBean.class);
                    SPUtils.getPreferences(activity).putString(BaseConfig.UNION_ID, bean.getUnionid());
                    listener.onResult(status, "", bean);
                }else {
                    listener.onResult(status, "", null);
                }
            }
        });
    }
}
